package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 添加新的菜系
     * @param category
     * @return
     */
    @PostMapping
    public R save(@RequestBody Category category){
        log.info("添加菜");

        categoryService.save(category);

        return R.success();

    }

    /**
     * 分页查询 查询菜系
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(required = false , defaultValue = "1") int page,
                                  @RequestParam(required = false , defaultValue = "10") int pageSize){
        //构造分页条件
        Page<Category> pageInfo = new Page(page,pageSize);

        //构造排序条件
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        //执行查询
        categoryService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 删除菜系 通过ID
     * 但是有关联的菜系 不能删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete( @PathVariable Long id){
        log.info("删除菜系 通过id");
        //原来的代码
        //categoryService.removeById(id);
        categoryService.deleteCategory(id);
        return R.success();
    }


    /**
     * 根据id 获取修改信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id){
        log.info("根据id 提示信息 方便修改");

        Category category = categoryService.getById(id);

        if (category != null){
            return R.success(category);
        }
        return R.error("没有查到该信息");
    }

    @PutMapping
    public R<Category> update(@RequestBody Category category){

        log.info("根据传过来的值 进行修改");

        categoryService.updateById(category);

        return R.success(category);
    }

    @GetMapping("/list")
    public R<List<Category>> List(Category category){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType() != null ,Category::getType,1);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }
}
